<template>
  <div class="">
    <el-form :inline="true">
      <div style="display: flex; justify-content: space-between;">
        <div>
          <el-form-item>
            <el-input v-model="title" clearable placeholder="请输入标题" style="width: 200px;" />
          </el-form-item>
          <!-- <el-form-item>
              <label>分类：</label>
              <el-select v-model="types" placeholder="分类" @change="onSearch">
                <el-option key="" label="全部" value="" />
                <el-option v-for="(item, index) in typeList" :key="index" :label="item.typename" :value="item.id" />
              </el-select>
            </el-form-item> -->
          <el-form-item>
            <label>状态：</label>
            <el-select v-model="state" placeholder="状态" @change="onSearch">
              <el-option label="全部" :value="-1" />
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
          </el-form-item>
        </div>
        <div>
          <el-form-item>
            <el-button type="primary" @click="onVisible(1)">新增</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <el-table v-loading="listLoading" :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center" />
      <el-table-column prop="sort" label="排序" width="60" align="center" />
      <el-table-column prop="typename" label="分类名称" align="center" />
      <el-table-column prop="headpic" label="封面" width="120" align="center">
        <template slot-scope="{row}">
          <el-image style="width: 80px; height: 80px" :src="row.headpic" :preview-src-list="row.picurl" />
        </template>
      </el-table-column>
      <el-table-column prop="title" show-overflow-tooltip label="标题" align="center" />
      <!-- <el-table-column prop="typeid" label="分类id" align="center" /> -->
      <!-- <el-table-column prop="newcode" label="编码" align="center" /> -->
      <el-table-column prop="content_abstract" show-overflow-tooltip label="摘要" align="center" />
      <el-table-column prop="state" label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" :active-value="1" :inactive-value="2"
            @change="(val) => { return SetValid(val, scope.row, 'state') }" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="onVisible(2, scope.row)">编辑</el-button>
          <!-- <el-button size="mini" type="danger" @click="onDelete(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="block " style="padding-top: 20px;">
      <el-pagination background :current-page="PageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="totalCount" @size-change="idx => { pageSize = idx }"
        @current-change="idx => { PageIndex = idx }" />
    </div>

    <!-- 新增 -->
    <el-dialog width="1000px" :close-on-click-modal="false" :title="visibleType == 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible" @open="openDialog" @closed="handleClose">
      <el-form id="forms" ref="forms" :rules="rulesModel" :model="form" label-width="100px"
        style="max-height: 600px;overflow-y: scroll;">
        <div>
          <el-form-item label="封面" prop="headImage">
            <UploadImageList :isImageList="false" :existImage="headImage" @success="val => headImage = val"
              :isDisplay="dialogVisible" />
          </el-form-item>
        </div>
        <!-- 选择分类 -->
        <el-form-item label="分类" prop="typeid">
          <el-select v-model="form.typeid" placeholder="分类" disabled @change="changetypeid">
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.typename" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title" style="width: 900px;">
          <el-input v-model="form.title" type="textarea" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="摘要" style="width: 900px;">
          <el-input v-model="form.content_abstract" type="textarea" placeholder="请输入摘要" />
        </el-form-item>
        <div style="display: flex;">
          <el-form-item label="编码">
            <el-input v-model="form.newcode" placeholder="请输入编码" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model.number="form.sort" :rows="2" placeholder="请输入排序" />
          </el-form-item>
        </div>
        <el-form-item label="启用/禁用" prop="state">
          <el-switch v-model="form.state" :active-value="1" :inactive-value="2" />
        </el-form-item>
        <div>
          <el-form-item label="内容" style="width: 900px;">
            <editor v-model="form.content" />
            <!-- <Tinymce v-model="form.content"/> -->
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="onEdit(1)">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
  
<script>
import { getToken } from '@/utils/auth'
import editor from '../../../components/Editor/index.vue'
import Tinymce from '../../../components/Tinymce'
import { mapState } from 'vuex'
import {
  GetTypes,
  GetNews,
  AddEditNews,
  DeleteNews,
  SetState,
  FirstNews
} from '@/api/news.js'
import ipConfig from '../../../../ip-config.js'
const tidArrPass = (rule, value, callback) => {
  if (value.length < 2) {
    callback(new Error('请选择到一级分类'))
  } else {
    callback()
  }
}
export default {
  name: 'Name',
  components: { editor,Tinymce },
  props: {
    types: {
      default: '1',
      type: String
    }
  },
  data() {
    return {

      loading: false,
      title: '',
      state: -1,
      typeList: [],
      listLoading: false,
      tableData: [],
      totalCount: 0,
      PageIndex: 1,
      pageSize: 10,

      dialogVisible: false,
      visibleType: '',
      form: {},
      headImage: '', // 修改时显示的图片路径
      rulesModel: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content_abstract: [
          { required: true, message: '请输入摘要', trigger: 'blur' }
        ],
        tidArr: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        newcode: [
          { required: true, message: '请输入编码', trigger: 'blur' }
        ],
        // typeid: [{ required: true, message: '选择分类', trigger: 'blur' }]
        // headImage: [
        //   { required: true, message: '请上传封面', trigger: 'blur' }
        // ]
      },
    }
  },
  computed: {},
  watch: {
    PageIndex(val) {
      console.log(val)
      this.getData()
    },
    types(){
      this.getData()
    }
  },
  mounted() {
    // this.getData()
    this.getPid()
  },
  methods: {
    onSearch() {
      this.PageIndex = 1
      this.getData()
    },
    setForm() {
      this.form = {
        id: 0,
        picurl: '',
        typeid: Number(this.types),
        sort: 0,
        newcode: '',
        title: '',
        content_abstract: '',
        ctime: new Date(),
        state: 1,
        content: '',
        typename: ''
      }
    },
    // 获取分类
    async getPid() {
      const { list } = await GetTypes({
        PageIndex: 1,
        PageSize: '10000'
      })
      this.typeList = list
      console.log(this.typeList)
    },
    changetypeid(eve) {
      this.typeList.forEach(item => {
        if (item.id == eve) {
          // if (this.visibleType == 1) {
          //   this.form.newcode = item.typecode;
          // }
          this.form.typename = item.typename
        }
      })
    },
    // 状态
    async SetValid(val, item, type) {
      try {
        console.log(item)
        const confirm = await this.$confirm('确定修改状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (confirm == 'confirm') {
          const { success, msg } = await SetState({
            id: item.id,
            valid: val
          })
          if (success) {
            this.getData()
          }
          this.$message({
            message: msg,
            type: success ? 'success' : 'error'
          })
        }
      } catch (e) {
        // 取消
        console.log(e)
        this.getData()
      }
    },
    // 删除
    async onDelete(item) {
      try {
        console.log(item)
        const confirm = await this.$confirm('确定删除该条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (confirm == 'confirm') {
          const { success, msg } = await DeleteNews([item.id])
          if (success) {
            this.getData()
          }
          this.$message({
            message: msg,
            type: success ? 'success' : 'error'
          })
        }
      } catch (e) {
        // 取消
        console.log(e)
        this.getData()
      }
    },
    // 编辑
    onEdit() {
      this.$refs['forms'].validate(async valid => {
        if (valid) {
          this.form.state = Number(this.form.state) || 0
          try {
            console.log(this.form)
            this.form.picurl = this.headImage
            this.loading = true
            const { success, msg } = await AddEditNews(this.form)
            this.loading = false
            if (success) {
              this.dialogVisible = false
              this.getData()
            }
            this.$message({
              message: msg,
              type: success ? 'success' : 'error'
            })
          } catch (error) {
            this.loading = false
          }
        } else {
          return false
        }
      })
    },
    // 关闭前
    handleClose() {
      this.setForm()
      this.$refs.forms.resetFields()
      this.$refs.forms.clearValidate()
      this.headImage = ''
      console.log(this.form)
    },
    openDialog() {
      this.$nextTick(() => {
        document.getElementById('forms').scrollTop = 0
      })
    },
    // 打开前
    async onVisible(type, item = {}) {
      this.visibleType = type
      this.setForm()
      this.changetypeid(this.types);
      if (type == 2) {
        const data = await FirstNews({
          id: item.id
        })

        this.form = { ...data }
        console.log(this.form)
        this.headImage = this.form.picurl[0]
      }
      this.dialogVisible = true
    },
    /**主列表 */
    async getData() {
      this.listLoading = true
      const { list, pageIndex, totalCount } = await GetNews({
        title: this.title,
        typeid: this.types || 1,
        state: this.state,
        PageIndex: this.PageIndex,
        PageSize: this.pageSize
      })
      this.totalCount = totalCount
      this.tableData = list
      console.log(list)
      this.listLoading = false
    }
  }
}
</script>
  
<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
  background: oldlace;
}

// 上传图片相关样式
.avatar-uploader .el-upload {
  width: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
</style>
  